<template>
  <el-card class="my-tasks-container">
    <!-- 任务类型切换 -->
    <el-card class="tab-card" shadow="never">
      <el-input v-model="query.name" placeholder="输入任务名称" style="width: 250px; margin-right: 10px"></el-input>
      <el-button icon="Search" type="primary" @click="handleSearch" style="margin-right: 10px">查询</el-button>

      <el-radio-group v-model="activeTab" @change="handleTabChange">
        <el-radio-button value="published">我发布的</el-radio-button>
        <el-radio-button value="accepted">我接取的</el-radio-button>
      </el-radio-group>

      <!-- 状态筛选 -->
      <div style="margin-top: 16px">
        <el-checkbox-group v-model="statusFilter" @change="handleSearch">
          <el-checkbox :value="1">待接单</el-checkbox>
          <el-checkbox :value="2">进行中</el-checkbox>
          <el-checkbox :value="3">已完成</el-checkbox>
          <el-checkbox :value="4">已取消</el-checkbox>
          <el-checkbox :value="5">已关闭</el-checkbox>
        </el-checkbox-group>
      </div>
    </el-card>

    <!-- 任务列表 -->
    <div style="margin-top: 20px">
      <el-row v-loading="loading" :gutter="20">
        <el-col v-for="task in taskList" :key="task.id" :span="12">
          <el-card class="task-item-card" shadow="hover">
            <div class="task-item-header">
              <div class="task-basic-info">
                <h3 class="task-name">{{ task.name }}</h3>
                <div class="task-tags">
                  <el-tag effect="plain" size="small">
                    {{ getTaskTypeName(task.type) }}
                  </el-tag>
                  <el-tag :type="getStatusColor(task.status)" size="small" style="margin-left: 8px">
                    {{ getStatusName(task.status) }}
                  </el-tag>
                  <el-tag v-if="task.isAbnormal" size="small" style="margin-left: 8px" type="danger">
                    异常
                  </el-tag>
                </div>
              </div>
              <div class="task-reward">¥{{ task.reward }}</div>
            </div>

            <el-text class="task-desc" line-clamp="2">{{ task.description }}</el-text>

            <!-- 进行中任务显示进度 -->
            <div v-if="task.status === 2" class="progress-section">
              <div class="progress-header">
                <span>任务进度</span>
                <span>{{ task.progress }}%</span>
              </div>
              <el-progress :percentage="task.progress" :stroke-width="8"/>
              <div class="progress-actions">
                <el-button v-if="task.acceptedByMe" size="small" @click="handleUpdateProgress(task)">
                  更新进度
                </el-button>
                <el-button v-if="task.acceptedByMe && task.isAbnormal === 0" size="small" type="warning"
                           @click="handleReportAbnormal(task)">
                  报告异常
                </el-button>
              </div>
            </div>

            <div class="task-item-footer">
              <div class="task-time-info">
                <span>创建时间：{{ task.createTime }}</span>
                <span v-if="task.acceptTime">接单时间：{{ task.acceptTime }}</span>
                <span>截止时间：{{ task.deadline }}</span>
              </div>
              <div class="task-item-actions">
                <el-button v-if="task.taskStages.length === 5 && task.status === 2 && task.publishedByMe" type="success"
                           @click="handleFinish(task)">
                  确认完成
                </el-button>
                <el-button v-if="task.status === 2" type="primary" @click="handleChat(task)">在线沟通</el-button>
                <el-button icon="view" @click="handleViewDetail(task)">
                  查看详情
                </el-button>
                <el-button
                    v-if="activeTab === 'published' && task.status === 1"
                    icon="edit"
                    type="primary"
                    @click="handleEditTask(task)"
                >
                  编辑
                </el-button>
                <el-button
                    v-if="task.status === 1"
                    icon="delete"
                    type="danger"
                    @click="handleCancelTask(task)"
                >
                  取消
                </el-button>
                <el-button
                    v-if="task.status === 4 || task.status === 5"
                    icon="delete"
                    type="danger"
                    @click="handleDeleteTask(task)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-empty v-if="!loading && taskList.length === 0" description="暂无任务数据"/>
    </div>

    <!-- 分页 -->
    <el-row justify="center" style="margin-top: 30px">
      <el-pagination
          v-model:current-page="pageInfo.current"
          v-model:page-size="pageInfo.size"
          :page-sizes="[10, 20, 30, 50]"
          :total="pageInfo.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-row>

    <!-- 任务详情弹窗 -->
    <TaskDetailDialog
        v-model="detailDialogVisible"
        :task-id="selectedTaskId"
    />

    <!-- 编辑任务弹窗 -->
    <PublishTaskDialog
        v-model="editDialogVisible"
        :task-data="editTaskData"
        @published="handleTaskUpdated"
    />

    <!-- 进度更新弹窗 -->
    <ProgressUpdateDialog
        v-model="progressDialogVisible"
        :task-data="selectedTask"
        @updated="handleProgressUpdated"
    />
  </el-card>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import request from '@/utils/request'
import TaskDetailDialog from '@/components/TaskDetailDialog.vue'
import PublishTaskDialog from '@/components/PublishTaskDialog.vue'
import ProgressUpdateDialog from '@/components/ProgressUpdateDialog.vue'
import {confirm} from "@/utils/utils.js";
import {useRouter} from "vue-router";

// 响应式数据
const loading = ref(false)
const query = reactive({
  name: ''
})
const taskList = ref([])
const activeTab = ref('published')
const statusFilter = ref([2])
const detailDialogVisible = ref(false)
const editDialogVisible = ref(false)
const progressDialogVisible = ref(false)
const selectedTaskId = ref(null)
const selectedTask = ref({})
const editTaskData = ref({})

// 分页信息
const pageInfo = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 获取任务列表
const handleGetTaskList = async () => {
  loading.value = true

  const param = {}
  if (activeTab.value === 'published') {
    param.publishedByMe = true
  } else {
    param.acceptedByMe = true
  }
  param.name = query.name

  if (statusFilter.value.length > 0) {
    param.statusList = statusFilter.value
  }

  const requestData = {
    page: pageInfo.current,
    size: pageInfo.size,
    param,
    orders: [{column: 'createTime', asc: false}]
  }

  const data = await request.post('/task/page', requestData)
  taskList.value = data.records
  pageInfo.total = data.total
  loading.value = false
}

// 切换标签
const handleTabChange = () => {
  pageInfo.current = 1
  handleGetTaskList()
}

// 搜索
const handleSearch = () => {
  pageInfo.current = 1
  handleGetTaskList()
}

// 分页处理
const handleSizeChange = (size) => {
  pageInfo.size = size
  pageInfo.current = 1
  handleGetTaskList()
}

const handleCurrentChange = (current) => {
  pageInfo.current = current
  handleGetTaskList()
}

const handleFinish = (task) => {
  confirm('是否确认完成任务', async () => {
    await request.put('/task', {
      id: task.id,
      status: 3,
    })
    ElMessage.success('成功完成任务')
    await handleGetTaskList()
  })
}

const router = useRouter()
const handleChat = async (task) => {
  const id = await request.post('/chat/createSession', {
    businessId: task.id,
    businessType: 1,
    userId: task.publishedByMe ? task.acceptorId : task.publisherId
  })
  await router.push(`/userHome/chatRoom?id=${id}`)
}

// 查看详情
const handleViewDetail = (task) => {
  selectedTaskId.value = task.id
  detailDialogVisible.value = true
}

// 编辑任务
const handleEditTask = (task) => {
  editTaskData.value = {...task}
  editDialogVisible.value = true
}

// 取消任务
const handleCancelTask = async (task) => {
  try {
    await ElMessageBox.confirm('确认取消该任务？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await request.put('/task', {
      id: task.id,
      status: 4
    })
    ElMessage.success('任务已取消')
    await handleGetTaskList()
  } catch {
    // 用户取消
  }
}

// 删除任务
const handleDeleteTask = async (task) => {
  try {
    await ElMessageBox.confirm('确认删除该任务？删除后无法恢复', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await request.delete(`/task/${task.id}`)
    ElMessage.success('任务已删除')
    await handleGetTaskList()
  } catch {
    // 用户取消
  }
}

// 更新进度
const handleUpdateProgress = (task) => {
  selectedTask.value = task
  progressDialogVisible.value = true
}

// 报告异常
const handleReportAbnormal = async (task) => {
  try {
    const {value: reason} = await ElMessageBox.prompt('请输入异常原因', '报告异常', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputType: 'textarea'
    })

    await request.post('/task/abnormal', {
      taskId: task.id,
      reason
    })

    ElMessage.success('异常报告已提交')
    await handleGetTaskList()
  } catch {
    // 用户取消
  }
}

// 任务更新成功
const handleTaskUpdated = () => {
  ElMessage.success('任务更新成功')
  handleGetTaskList()
}

// 进度更新成功
const handleProgressUpdated = () => {
  ElMessage.success('进度更新成功')
  handleGetTaskList()
}

// 工具函数
const getTaskTypeName = (type) => {
  const types = {1: '代购', 2: '代取快递', 3: '代办事务'}
  return types[type] || '未知'
}

const getStatusName = (status) => {
  const statuses = {1: '待接单', 2: '进行中', 3: '已完成', 4: '已取消', 5: '已关闭'}
  return statuses[status] || '未知'
}

const getStatusColor = (status) => {
  const colors = {1: 'warning', 2: 'primary', 3: 'success', 4: 'danger', 5: 'info'}
  return colors[status] || 'info'
}

// 初始化
onMounted(() => {
  handleGetTaskList()
})
</script>

<style scoped>
.my-tasks-container {
  width: 1500px;
  margin: 0 auto;
}

.tab-card {
  border-radius: 8px;
}

.task-item-card {
  margin-bottom: 16px;
  border-radius: 8px;
}

.task-item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.task-name {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #303133;
}

.task-reward {
  font-size: 18px;
  font-weight: 600;
  color: #ff4757;
}

.task-desc {
  color: #606266;
  margin-bottom: 16px;
  line-height: 20px;
}

.progress-section {
  margin-bottom: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-weight: 500;
}

.progress-actions {
  margin-top: 12px;
  display: flex;
  gap: 8px;
}

.task-item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.task-time-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 12px;
  color: #909399;
}

.task-item-actions {
  display: flex;
}
</style>
